using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace SmartLink.Infrastructure
{
    public class ServiceControllerHelper
    {
        /// <summary>
        /// 服务是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool IsExistWindowsServer(string serviceName)
        {
            bool result = false;
            ServiceController[] controllers = ServiceController.GetServices();
            int nNum = controllers.Length;
            try
            {
                for (int i = 0; i <= (nNum - 1); i++)
                {
                    if ((controllers[i].ServiceName.ToUpper() == serviceName.ToUpper()))
                    {
                        result = true;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 服务是否运行
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool IsRuningWindowsServer(string serviceName)
        {
            bool result = false;
            ServiceController[] controllers = ServiceController.GetServices();
            int nNum = controllers.Length;
            try
            {
                for (int i = 0; i <= (nNum - 1); i++)
                {
                    if (controllers[i].ServiceName.ToUpper() == serviceName.ToUpper())
                    {
                        if (controllers[i].Status == ServiceControllerStatus.Running)
                        { result = true; }
                        else
                        {
                            result = false;
                        }
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                result = false;
            }
            return result;
        }
    }
}
